import os
import random
import time
from time import sleep

import tornado.gen
import tornado.ioloop
import tornado.web
from flask import Flask
from tornado.wsgi import WSGIContainer

from config.logger_config import logger


class MainHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        # 模拟一个耗时的任务 
        yield self.long_task()
        self.write("Task  completed!")

    @tornado.gen.coroutine
    def long_task(self):
        # 模拟一个耗时的I/O操作 
        yield tornado.gen.sleep(5)

flask_app = Flask(__name__)

# http://localhost:5600/flask/index
global_variable = random.randint(1,  1000)

@flask_app.route('/flask/index')
def index():
    worker_pid = os.getpid()  # 获取当前worker的PID
    logger.debug(f"global_variable:{global_variable}, invoke api {time.time()} by worker PID:{worker_pid}")
    sleep(2)
    return f"Hello, World! {time.time()}"

def make_app():
    tornado_app = tornado.web.Application([
        (r"/tornado", MainHandler),
    ])

    # 将Flask应用包装成Tornado的WSGIContainer
    flask_container = WSGIContainer(flask_app)

    # 将Flask应用和Tornado应用合并
    tornado_app.add_handlers(".*$", [
        (r"/flask/.*", tornado.web.FallbackHandler, dict(fallback=flask_container)),
    ])

    return tornado_app

app = make_app()
if __name__ == "__main__":
    app.listen(5600)
    tornado.ioloop.IOLoop.current().start()  